package cc.rengu.redp.flowable.service.modelValidator;

import cc.rengu.redp.flowable.domain.CustomProcess;
import cc.rengu.redp.flowable.domain.CustomStartNode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.StartEvent;
import org.flowable.validation.ValidationError;
import org.flowable.validation.validator.ProcessLevelValidator;

import java.util.List;

public class CustomStartNodeValidator extends ProcessLevelValidator {
    @Override
    protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> list) {

        List<StartEvent> startEvents = process.findFlowElementsOfType(StartEvent.class);
        if (startEvents.size() != 1) {
            list.add(GenValidateError.get(null, null, "起始事件应只有一个", true));
        }

        CustomProcess customProcess = JSON.parseObject(process.getDocumentation(), CustomProcess.class);
        List<String> procUsers = process.getCandidateStarterUsers();
        List<String> procGroups = process.getCandidateStarterGroups();
        if (CustomProcess.PROCESS_USAGE_TYPE_APPLY_FORM.equals(customProcess.getQryFormType())) {
            // 用户权限验证
            if ((procUsers == null || procUsers.isEmpty()) && (procGroups == null || procGroups.isEmpty())) {
                list.add(GenValidateError.get(null, null, "用户表单启动模式下，存在未关联权限的开始事件", true));
            }

            // 表单信息验证
            StartEvent startEvent = startEvents.get(0);
            CustomStartNode customStartNode = JSONObject.parseObject(startEvent.getDocumentation(), CustomStartNode.class);
            if (StringUtils.isBlank(customStartNode.getFormIcon()) ||
                    StringUtils.isBlank(customStartNode.getFormTitle()) ||
                    StringUtils.isBlank(customStartNode.getFormType()) ||
                    (StringUtils.isBlank(customStartNode.getFormId()) && StringUtils.isBlank(customStartNode.getFormPath()))
            ) {
                list.add(GenValidateError.get(startEvent.getId(), startEvent.getName(), "用户表单启动模式下，需填写表单关联信息", true));
            }
        }
    }
}
